//
//  BMKMapViewController.m
//  百度地图
//
//  Created by ljm on 2017/7/7.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "BMKMapViewController.h"

@interface BMKMapViewController ()
<UITableViewDelegate,UITableViewDataSource,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    
    /** 地图 **/
    BMKMapView *_mapView;
    
    /** 定位 **/
    BMKLocationService *_locationServer;
    
    /** 大头针 **/
    BMKPointAnnotation *_pointAnnotation;
    
    /** 编码 **/
    BMKGeoCodeSearch *_geoCodeSearch;
    
    /** 反编码 **/
    BMKReverseGeoCodeOption *_reverGeocode;
    
    /** 拖动地图的手势 **/
    UIPanGestureRecognizer *_panMapView;
    
    UIView *_searchView;
    
    /** 定位按钮 **/
    UIButton *_locationBtn;
    
    UITableView *_nearTableview;
    NSMutableArray *_nearArray;
    
    /** 纬度 **/
    NSString *_latitude;
    /** 经度 **/
    NSString *_longitude;
    
    /** 街道名称 **/
    NSString *_streeName;
    /** 城市 **/
    NSString *_city;
    /** 地址 **/
    NSString *_address;
    
    /** 筛选重复的地址 **/
    NSString *_sameAddress;
    
    /** 拖动结束后才显示周边 **/
    BOOL isOverMapPanGestureRecognizer;
    
    /** 判断大头针仅显示一次 **/
    BOOL isShowOnlyOneAnnotation;
    
}

@end

@implementation BMKMapViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _mapView.delegate = self;
//    _locationServer.delegate = self;
    
    Navigationbar_color = RGB(78, 184, 43);

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    _mapView.delegate = nil;
    
    Navigationbar_color = [UIColor clearColor];
//    _locationServer.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"搜索";
    
    [self setupUI];
    
    /** 判断是否已经结束拖动 **/
    isOverMapPanGestureRecognizer = NO;
    
    /** 判断是否只显示一次大头针 **/
    isShowOnlyOneAnnotation = NO;
    
    /** 一开始是否隐藏定位按钮 **/
    _locationBtn.hidden = YES;
    
    /** 初始化数组 **/
    _nearArray = [NSMutableArray arrayWithCapacity:1];
    
    /** 加载地图 **/
    [self loadMapView];
    
    /** 定位 **/
    [self loadLocation];
    
    /** 滑动地图 **/
    [self scrollMapView];
    
    /** 加载周边信息 **/
    [self loadNearTableview];
    
    
}

#pragma mark -- 设置界面
- (void) setupUI
{
 
    #pragma mark -- 底层灰色view
    _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, screenWidth, 60)];
    _searchView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_searchView];
    
    
    #pragma mark -- 搜索框
    UILabel *_tipLab            =   [[UILabel alloc] initWithFrame:CGRectMake(5,
                                                                              8,
                                                                              screenWidth - 5 * 2,
                                                                              _searchView.frame.size.height - 8 * 2)];
    _tipLab.backgroundColor     =   [UIColor whiteColor];
    _tipLab.layer.cornerRadius  =   5;
    _tipLab.layer.masksToBounds =   YES;
    _tipLab.text                =   @"请输入你想搜索的地点";
    _tipLab.textColor           =   [UIColor darkGrayColor];
    _tipLab.textAlignment       =   NSTextAlignmentCenter;
    [_searchView addSubview     :   _tipLab];
    
    UITapGestureRecognizer *_searchGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchWichClicked)];
    [_searchView addGestureRecognizer:_searchGesture];
    
}

#pragma mark -- 加载地图
- (void) loadMapView
{
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0,
                                                            _searchView.frame.origin.y + _searchView.frame.size.height,
                                                            screenWidth,
                                                            screenHeight * 0.4)];
    /** 设置地图类型 **/
//    [_mapView setMapType:BMKMapTypeStandard];
    _mapView.mapType        =   BMKMapTypeStandard;
    
    /** 设置百度地图的logo **/
//    [_mapView setLogoPosition:BMKLogoPositionRightBottom];
    _mapView.logoPosition   =   BMKLogoPositionRightBottom;
    
    /** 设置地图大小比例 **/
    [_mapView setZoomLevel  :   12];
    
    /** 设置定位类型 **/
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;

    [self.view addSubview   :   _mapView];
    
}


#pragma mark -- 滑动地图
- (void) scrollMapView
{
    _panMapView = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMapViewClicked:)];
    [_mapView addGestureRecognizer:_panMapView];
}

#pragma mark -- 定位
- (void)loadLocation
{
    
    UIImageView *labelImage = [[UIImageView alloc] initWithFrame:CGRectMake((
                                                                             _mapView.frame.size.width - 25) / 2,
                                                                            _mapView.frame.size.height / 2 - 33,
                                                                            25,
                                                                            33)];
    labelImage.image = [UIImage imageNamed:@"icon_baidu_marker"];
    [_mapView addSubview:labelImage];
    
    
    /** 设置定位 **/
    _locationBtn = [[UIButton alloc] initWithFrame:CGRectMake(5,
                                                              _mapView.frame.size.height - 5 - 30,
                                                              40,
                                                              30)];
    _locationBtn.backgroundColor        =   [UIColor lightGrayColor];
    [_locationBtn setTitle              :   @"定位" forState:UIControlStateNormal];
    [_locationBtn setTitleColor         :   [UIColor darkTextColor] forState:UIControlStateNormal];
    [_locationBtn addTarget:self action :   @selector(locationBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview                :   _locationBtn];
    
    
    _locationServer             =   [[BMKLocationService alloc] init];
    _locationServer.delegate    =   self;
    [_locationServer startUserLocationService];
    
    
    _geoCodeSearch              =   [[BMKGeoCodeSearch alloc] init];
    _geoCodeSearch.delegate     =   self;
}

#pragma mark -- 定位事件，重新定位到当前位置
- (void) locationBtnClicked
{
    
    
    CLLocationCoordinate2D coor  = _pointAnnotation.coordinate;
    
    BMKCoordinateRegion region;
    region.center.latitude      =   coor.latitude;
    region.center.longitude     =   coor.longitude;
    region.span.latitudeDelta   =   0;
    region.span.longitudeDelta  =   0;
    [UIView animateWithDuration:1 animations:^{
        if (_mapView) {
            _mapView.region     = region;
        }
    }];
    
}


#pragma mark -- 加载滑动地图的事件
- (void) panMapViewClicked :(UIPanGestureRecognizer *) pan
{
    isOverMapPanGestureRecognizer = YES;
    [_mapView removeGestureRecognizer:_panMapView];
}

#pragma mark -- 当地图停止拖动时才显示周边信息
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    if (isOverMapPanGestureRecognizer == NO) {
        return;
    }
    
    /**
     *    把停止拖动时地图的中心点转化为经纬度
     */
    BMKCoordinateRegion region = _mapView.region;
    
    /**
     *    初始化地理位置编码，注意：反地理位置编码必须在地理位置编码之后
     */
    /** 初始化地理位置编码 **/
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _geoCodeSearch.delegate = self;
    
    /** 初始化反地理位置编码 **/
    _reverGeocode = [[BMKReverseGeoCodeOption alloc] init];
    
    _reverGeocode.reverseGeoPoint = CLLocationCoordinate2DMake(region.center.latitude, region.center.longitude);
    
    /** 调用反地理编码 **/
    BOOL flag = [_geoCodeSearch reverseGeoCode:_reverGeocode];
    if (flag) {
        NSLog(@"------------------------反地理编码成功-----------------------\n");
//        [_locationServer startUserLocationService];
    }else
    {
        NSLog(@"++++++++++++++++++++++++反地理编码失败++++++++++++++++++++++++\n");
        [_locationServer startUserLocationService];
    }
    
}

#pragma mark -- 反向地理编码
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (result) {
        [_nearArray removeAllObjects];
        
        _address    =   result.address;
        _streeName  =   result.addressDetail.streetName;
        _city       =   result.addressDetail.city;
        _latitude   =   [NSString stringWithFormat:@"%f",result.location.latitude];
        _longitude  =   [NSString stringWithFormat:@"%f",result.location.longitude];
        
        NSDictionary *dic = @{@"address"    :   _address,
                              @"name"       :   _streeName,
                              @"locationX"  :   _latitude,
                              @"locationY"  :   _longitude,
                              @"city"       :   _city};
        
        [_nearArray addObject:dic];
        
    }else
    {
        NSLog(@"抱歉，未找到相应结果");
    }
    
    /**
     *    获取周边信息
     */
    NSInteger index = 0;
    for (BMKPoiInfo *info in result.poiList) {
        NSDictionary *dic = @{@"address"    :   info.address,
                              @"name"       :   info.name,
                              @"locationX"  :   [NSString stringWithFormat:@"%f",info.pt.latitude],
                              @"locationY"  :   [NSString stringWithFormat:@"%f",info.pt.longitude],
                              @"city"       :   info.city};
        [_nearArray addObject:dic];
        index ++ ;
        
        if (index == result.poiList.count) {
            
            if (isShowOnlyOneAnnotation == NO) {
                isShowOnlyOneAnnotation = YES;
                _locationBtn.hidden     = NO;
                
                /** 地图定位显示 **/
                BMKCoordinateRegion region;
                region.center.latitude      = [_latitude doubleValue];
                region.center.longitude     = [_longitude doubleValue];
                region.span.latitudeDelta   = 0;
                region.span.longitudeDelta  = 0;
                [UIView animateWithDuration:1 animations:^{
                    if (_mapView) {
                        _mapView.region = region;
                    }
                }];
                
                _pointAnnotation    = [[BMKPointAnnotation alloc]init];
                CLLocationCoordinate2D coor;
                coor.latitude       = [_latitude doubleValue];
                coor.longitude      = [_longitude doubleValue];
                _pointAnnotation.coordinate = coor;
                _pointAnnotation.title = _streeName;
                [_mapView addAnnotation:_pointAnnotation];
            
            }
            [_nearTableview reloadData];
        }
    }
}

#pragma mark -- 标注大头针
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        /** 标注新的大头针 **/
        BMKPinAnnotationView *newPinAnnotationView = [[BMKPinAnnotationView alloc]
                                                      initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newPinAnnotationView.pinColor       =   BMKPinAnnotationColorRed;
        newPinAnnotationView.animatesDrop   =   YES;
        
        return newPinAnnotationView;
    }
    return nil;
}

#pragma mark -- 定位的代理,要使地图在加载出来时候就在当前位置必须实现这个代理
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    /**
     *    初始定位失败
     */

    [_locationServer stopUserLocationService];
    
    /**
     *    初始化反地理编码
     */
    /** 初始化地理编码 **/
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _geoCodeSearch.delegate = self;
    
    /** 初始化反地理编码 **/
    _reverGeocode = [[BMKReverseGeoCodeOption alloc] init];
    /** 需要反地理编码的位置 **/
    _reverGeocode.reverseGeoPoint = CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    /** 调用反地理编码 **/
    BOOL flag = [_geoCodeSearch reverseGeoCode:_reverGeocode];
    if (flag) {
        NSLog(@"------------------------反地理初始化编码成功-----------------------\n");
        //        [_locationServer startUserLocationService];
    }else
    {
        NSLog(@"++++++++++++++++++++++++反地理初始化编码失败++++++++++++++++++++++++\n");
        [_locationServer startUserLocationService];
    }
    /**
     *    直接调用这个方法也是可以的;注意，使用这个方法会导致大头针出现的位置是第一次拖拽结束后的位置；而使用上边的方法大头针出现的位置是地图加载完成后的中间位置
     */
//    BMKCoordinateRegion region;
//    region.center.latitude = userLocation.location.coordinate.latitude;
//    region.center.longitude = userLocation.location.coordinate.longitude;
//    
//    region.span.latitudeDelta = 0;
//    region.span.longitudeDelta = 0 ;
//    
//    if (_mapView) {
//        _mapView.region = region;
//    }
//    
//    [_locationServer stopUserLocationService];
//    
}

#pragma mark -- 搜索actions
- (void) searchWichClicked
{
    TitleTableViewController *titlevc = [[TitleTableViewController alloc] init];
    NSDictionary *dic = @{};
    if (_address!= nil && _latitude!= nil && _longitude!= nil && _city!= nil) {
        if (_streeName == nil) {
            _streeName = _address;
        }
        dic = @{@"address"  :   _address,
                @"name"     :   _streeName,
                @"lat"      :   _latitude,
                @"lon"      :   _longitude,
                @"city"     :   _city};
    }
    
    titlevc.searchDict = dic;
    titlevc.titleSearch = ^(NSDictionary *searchDic) {
        self.addressBlock(searchDic);
        [self.navigationController popViewControllerAnimated:YES];
    };
    [self.navigationController pushViewController:titlevc animated:NO];
    
}

#pragma mark -- 加载周边信息
- (void) loadNearTableview
{
    _nearTableview = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   _mapView.frame.origin.y + _mapView.frame.size.height, screenWidth,
                                                                   screenHeight - 64 - _searchView.frame.size.height - _mapView.frame.size.height)
                                                  style:UITableViewStylePlain];
    _nearTableview.delegate = self;
    _nearTableview.dataSource = self;
    [self.view addSubview:_nearTableview];
}


#pragma mark -- searchtableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return _dataArr.count;
    return _nearArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"myCell";
    TitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"TitleTableViewCell" owner:nil options:nil].firstObject;
    }
    
    cell.BMKMapLogo.image           =   [UIImage imageNamed:@"定位2"];
    cell.addressNameLab.text        =   [_nearArray[indexPath.row] objectForKey:@"name"];
    cell.addressDetailNameLab.text  =   [_nearArray[indexPath.row] objectForKey:@"address"];
    
    if (indexPath.row == 0) {
        cell.BMKMapLogo.image               = [UIImage imageNamed:@"定位1"];
        cell.addressNameLab.textColor       = [UIColor orangeColor];
        cell.addressDetailNameLab.textColor = [UIColor orangeColor];
    }

    return cell;
}

#pragma mark -- UItableview的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = _nearArray[indexPath.row];
    
    _address    =   [dic objectForKey:@"address"];
    _streeName  =   [dic objectForKey:@"name"];
    _city       =   [dic objectForKey:@"city"];
    _latitude   =   [dic objectForKey:@"locationX"];
    _longitude  =   [dic objectForKey:@"locationY"];
    
    
    if (_address != nil && _latitude != nil && _longitude != nil && _city != nil) {
        if (_streeName == nil) {
            _streeName = _address;
        }
        NSDictionary *dict = @{@"address"   :   _address,
                               @"name"      :   _streeName,
                               @"lat"       :   _latitude,
                               @"lon"       :   _longitude,
                               @"city"      :   _city};
        self.addressBlock(dict);
        [self.navigationController popViewControllerAnimated:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


@end
